import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
import { EntityManager } from 'typeorm';
import { User } from './entities/user.entity';
import { LoginUserDto } from './dto/login-user.dto';
import { JwtService } from '@nestjs/jwt';

@Injectable()
export class UserService {
  // 这段代码其实是注入的一个实体管理器，这个实体管理器是typeorm的，用于管理数据库的
  constructor(
    private readonly entityManager: EntityManager,
    private readonly jwtService: JwtService,
  ) {}

  // 注册
  create(createUserDto: CreateUserDto) {
    // 使用entityManager的save方法向User表中插入数据
    return this.entityManager.save(User, createUserDto);
  }

  // 登录
  async login(loginUserDto: LoginUserDto) {
    // 使用entityManager的findOne方法查询User表中的数据
    const user = await this.entityManager.findOne(User, {
      where: {
        username: loginUserDto.username,
        password: loginUserDto.password,
      },
    });

    if (!user) {
      throw new HttpException('用户名或密码错误', HttpStatus.BAD_REQUEST);
    }

    // 生成access_token，内容是用户名和id
    const access_token = this.jwtService.sign(
      {
        username: user.username,
        id: user.id,
      },
      {
        expiresIn: '30m', // 30分钟
      },
    );

    // 生成refresh_token，内容是id
    const refresh_token = this.jwtService.sign(
      {
        id: user.id,
      },
      {
        expiresIn: '7d', // 7天
      },
    );

    return { refresh_token, access_token };
  }

  // 刷新token
  async refreshToken(refresh_token: string) {
    console.log('refresh_token', refresh_token);
    try {
      // 验证refresh_token
      const decoded = this.jwtService.verify(refresh_token, {
        secret: 'secret',
      });

      // 获取用户信息
      const user = await this.entityManager.findOne(User, {
        where: {
          id: decoded.id,
        },
      });

      // 生成access_token
      const access_token = this.jwtService.sign(
        {
          username: user.username,
          id: decoded.id,
        },
        {
          expiresIn: '30m', // 30分钟
        },
      );

      // 生成refresh_token
      const newRefresh_token = this.jwtService.sign(
        {
          id: decoded.id,
        },
        {
          expiresIn: '7d', // 7天
        },
      );

      return { data: { refresh_token: newRefresh_token, access_token } };
    } catch (error) {
      throw new HttpException('refresh_token已过期', HttpStatus.BAD_REQUEST);
    }
  }

  // 获取用户信息
  async getUserInfo(id: number) {
    // 使用entityManager的findOne方法查询User表中的数据
    const user = await this.entityManager.findOne(User, {
      where: {
        id,
      },
    });

    if (!user) {
      throw new HttpException('用户不存在', HttpStatus.BAD_REQUEST);
    }

    return { data: user };
  }
}
